package com.google.code.coma;

import com.google.code.coma.Coma;
import com.google.code.coma.domain.Computer;
import com.google.code.coma.domain.LifeCycleStep;
import com.google.code.coma.rmi.RMIManager;
import com.google.code.coma.rmi.SelectAllSelector;
import com.google.code.coma.space.SelectAllSelectorCallback;
import com.google.code.coma.space.SpaceSelector;
import com.google.code.coma.space.util.SpaceManager;
import org.mozartspaces.core.*;

import java.net.URI;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Dominik Strasser, dominikstr@gmail.com
 */
public class CountFinishedComputers {

	public static void main(String... args) {
		if (args[0].equals("SPACE")) {
			URI spaceURI = URI.create("xvsm://localhost:4242");
			MzsCore core = DefaultMzsCore.newInstance(0);
			Capi capi = new Capi(core);

			spaceCount(spaceURI, "factory1", capi);
			spaceCount(spaceURI, "factory2", capi);
			spaceCount(spaceURI, "factory3", capi);
		} else if (args[0].equals("RMI")) {
			rmiCount("factory1");
			rmiCount("factory2");
			rmiCount("factory3");
		}
	}

	private static void rmiCount(String factory) {
		try {
			List<Computer> computers = RMIManager.getStorageService(factory + "_" + Coma.COMPUTER_CONTAINER).getSnapshot(new SelectAllSelector<Computer>());
			for (int i = 0; i < computers.size(); i++) {
				if (computers.get(i).getCurrent() != LifeCycleStep.FINISHED) {
					computers.remove(i);
					i--;
				}   
			}
			System.out.println("Factory " + factory + " contains " +
					computers.size()
					+ " finished computers");
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}

	private static void spaceCount(URI spaceURI, String factory, Capi capi) {
		try {
			ContainerReference containerReference = SpaceManager.getOrCreateNamedContainer(spaceURI, factory + "_" + Coma.COMPUTER_CONTAINER, capi);
			ArrayList<Computer> computers = capi.read(containerReference, new SpaceSelector(new SelectAllSelectorCallback()), MzsConstants.RequestTimeout.DEFAULT, null);
			for (int i = 0; i < computers.size(); i++) {
				if (computers.get(i).getCurrent() != LifeCycleStep.FINISHED) {
					computers.remove(i);
					i--;
				}
			}
			System.out.println("Factory " + factory + " contains " +
					computers.size()
					+ " finished computers");
		} catch (MzsCoreException e) {
			e.printStackTrace();
		}
	}
}
